#!/usr/bin/env node

const fs = require('fs'),
      log = console.log,
      cmd = process.argv[2],
      join = require('path').join,
      file = process.argv[3];

let path = 'sysFile';
function compare(p){
  return function(a,b){
    let value1 = a[p];
    let value2 = b[p];
    return value1 - value2;
  };
}
if(cmd == '-list'){
  let files = fs.readdirSync(path);
  let arr = files.filter(item => fs.statSync(join(path,item)).isFile());
  let brr = new Array();
  for(let i=0; i<arr.length; i++){
    let obj = new Object();
    obj.fileName = arr[i];
    obj.fileSize = fs.statSync(join(path,arr[i])).size.toString();
    brr.push(obj);
  }
  log(JSON.stringify(brr.sort(compare('fileSize')),null,1));
}

if(cmd == '-show'){
  let f = join(path,file);
  fs.readFile(f,(err,data)=> {
    if(err){
      console.error('该文件不存在');
      process.exit(1);            
    }else{
      log(data.toString('utf8'));        
    }
  });
}

function del(f){
  if(fs.statSync(f).isFile()){
    fs.unlinkSync(f);
  }else{
    let fis = fs.readdirSync(f);
    fis.forEach((item)=>{
      del(join(f,item));
    });
    fs.rmdirSync(f);
  }
}
if(cmd == '-del'){
  let f = join(path,file);
  if(!fs.existsSync(f)){
    log('该文件不存在');
    process.exit(2);
  }
  del(f);
  log(`${file} 删除成功`);
}
